// axios 配置
import axios from 'axios'
import {
    getCookie,
    delCookie
} from './cookie'
import GLOBAL from '../component/global.vue'
//qs
import qs from 'qs'
//qs
const $ajax = axios.create({
    baseURL: GLOBAL.WEB_SITE,
    // timeout: 30000
})

// http request 拦截器
$ajax.interceptors.request.use(
    config => {
        config.data = qs.stringify(config.data)
        config.headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        config.params = {
            'token': localStorage.getItem('token')
        }

        return config
    },
    err => {
        return Promise.reject(err)
    }
)

// http respone 拦截器
$ajax.interceptors.response.use(
    response => {
        if (response.data.code == 44001) {
            localStorage.removeItem('token');
            window.location.reload();
            return;
        }
        return response
    },
    error => {
        return Promise.reject(error.response.data)
    }
)

/**
 * get 请求方法
 * @param url
 * @param data
 * @return {Promise}
 */
export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        $ajax.get(url, {
            param: params
        }).then(response => {
            resolve(response.data)
        }, err => {
            reject(err)
        })
    })
}

/**
 * post 请求方法
 * @param url
 * @param data
 * @return {Promise}
 */
export function post(url, data = {}) {
    return new Promise((resolve, reject) => {
        $ajax.post(url, data).then(response => {
            console.group(url)
            console.log('%c 请求路径--->', 'color: #1ba01b', url)
            console.log('%c 请求参数--->', 'color: #1ba01b', data)
            console.log('%c 成功--->', 'color: #1ba01b', response.data)
            console.groupEnd()
            resolve(response.data)
        }, err => {
            console.group(url)
            console.error('%c 请求路径--->', url)
            console.error('%c 请求参数--->', data)
            console.error('%c 失败--->', err)
            console.groupEnd()
            reject(err)
        })
    })
}
